package com.yltrcc.blog.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yltrcc.blog.dao.NovelDao;
import com.yltrcc.blog.generate.domain.TipsMain;
import com.yltrcc.blog.generate.domain.TipsMainTagRel;
import com.yltrcc.blog.generate.domain.TipsTag;
import com.yltrcc.blog.generate.domain.TodoMain;
import com.yltrcc.blog.generate.mapper.TipsMainMapper;
import com.yltrcc.blog.generate.mapper.TipsTagMapper;
import com.yltrcc.blog.generate.service.TipsMainService;
import com.yltrcc.blog.generate.service.TipsMainTagRelService;
import com.yltrcc.blog.generate.service.TipsTagService;
import com.yltrcc.blog.model.model.ApiResponse;
import com.yltrcc.blog.model.model.BaseApiResponse;
import com.yltrcc.blog.model.enums.TipsStatusEnums;
import com.yltrcc.blog.model.model.TipsMainModel;
import com.yltrcc.blog.model.model.TipsMainVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.expression.Lists;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业微信 群推送APi
 */
@RestController
@RequestMapping(value = "/api/tips")
public class TipsApiController {

    @Autowired
    private TipsMainService tipsMainService;

    @Autowired
    private TipsMainTagRelService tipsMainTagRelService;

    @Autowired
    private TipsTagService tipsTagService;

    @Resource
    private TipsMainMapper tipsMainMapper;

    @Resource
    private TipsTagMapper tipsTagMapper;

    @Resource
    private NovelDao novelDao;

    @RequestMapping(method = RequestMethod.POST, value = "/saveTips")
    @ResponseBody
    public BaseApiResponse saveTips(@RequestBody TipsMainModel tipsMainModel) {

        if (!StringUtils.hasText(tipsMainModel.getContentMd())) {
            return new BaseApiResponse(500, 500, "没有需要保存的数据！！！");
        }
       try {
           //正常 回收站
           TipsMain tipsMain = new TipsMain();
           BeanUtils.copyProperties(tipsMainModel,tipsMain);
           tipsMain.setStatus(TipsStatusEnums.NORMAL.name());
           tipsMain.setCreateTime(new Date());
           tipsMain.setUpdateTime(new Date());

           String tagStr = tipsMainModel.getTagStr();
           List<String> tagStrList = new ArrayList<>();
           List<TipsTag> tags = new ArrayList<>();
           if (StringUtils.hasText(tagStr)) {
               String[] split = tagStr.split(",");
               tagStrList = Arrays.asList(split);
           }
           if (!CollectionUtils.isEmpty(tagStrList)) {
               //说明有标签
               tipsMain.setTagOrNot("1");
               tipsMainService.save(tipsMain);
               //查询 tag 表 将 id 和 tag 对应查询出来 没有的话就新增
               for (String tagName : tagStrList) {
                   if (!StringUtils.hasText(tagName)) {
                       continue;
                   }
                   TipsTag tipsTag = tipsTagMapper.selectOne(new QueryWrapper<TipsTag>().eq("tag_name", tagName));
                   if (tipsTag == null) {
                       //新增
                       tipsTag = new TipsTag();
                       tipsTag.setTagName(tagName);
                       tipsTagMapper.insert(tipsTag);
                   }
                   tags.add(tipsTag);
               }
               //查询关联数据
               //更新数据到关联表中。
               for (TipsTag tag: tags) {
                   TipsMainTagRel tipsMainTagRel = new TipsMainTagRel();
                   tipsMainTagRel.setTipsMainId(tipsMain.getId());
                   tipsMainTagRel.setTipsTagId(tag.getId());
                   tipsMainTagRelService.save(tipsMainTagRel);
               }
           }else {
               //说明没有标签
               tipsMain.setTagOrNot("0");
               tipsMainService.save(tipsMain);
           }
       }catch (DuplicateKeyException e) {
           return new BaseApiResponse(500, 500, "不可保存相同内容！！！");
       }catch (Exception e) {
           return new BaseApiResponse(500, 500, "未知异常，请联系管理员！！！");
       }

        return new BaseApiResponse();
    }

    /**
     * 显示所有小记
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getTips")
    public ApiResponse<TipsMainVo> getTips(Model model, @RequestParam(value = "page", defaultValue = "1") int page,
                                           @RequestParam(value = "limit", defaultValue = "8") int limit,
                                           @RequestParam(value = "status", defaultValue = "NORMAL") String status,
                                           @RequestParam(value = "tag", defaultValue = "") String tag) {
        Page<TipsMain> tipsMainPage = new Page<>();
        if (StringUtils.hasText(tag)) {
            QueryWrapper<TipsTag> wrapperTmp = new QueryWrapper<>();
            //update_time 降序  isAsc) 是否升序排列 true=asc，false=desc
            //查询
            wrapperTmp.eq("tag_name", tag);
            List<TipsTag> tags = tipsTagService.list(wrapperTmp);
            if (!CollectionUtils.isEmpty(tags)) {
                QueryWrapper<TipsMainTagRel> wrapperRelTmp = new QueryWrapper<>();
                //update_time 降序  isAsc) 是否升序排列 true=asc，false=desc
                //查询
                wrapperRelTmp.eq("tips_tag_id", tags.get(0).getId());
                List<TipsMainTagRel> list = tipsMainTagRelService.list(wrapperRelTmp);
                List<Integer> mainId = list.stream().map(TipsMainTagRel::getTipsMainId).collect(Collectors.toList());
                QueryWrapper<TipsMain> wrapperMain = new QueryWrapper<>();
                wrapperMain.in("id", mainId);
                List<TipsMain> tipsMainList = tipsMainService.list(wrapperMain);
                tipsMainPage.setRecords(tipsMainList);
            }
        }else {
            QueryWrapper<TipsMain> wrapper = new QueryWrapper<>();
            //update_time 降序
            wrapper.orderBy(true, false, "is_top")
                    .orderBy(true, false, "update_time");
            tipsMainPage = tipsMainService.page(new Page<>(page, limit), wrapper.eq("status", status));
        }


        //添加 对应的 tags
        List<TipsMain> records = tipsMainPage.getRecords();
        List<TipsMainVo> tipsMainVos = new ArrayList<>();
        if (page == 1) {
            //查询所有没有 tag 的数据 也就是 tagOrNot == 0 的数据
            List<Integer> allTips = novelDao.selectTips();
            if (!CollectionUtils.isEmpty(allTips)) {
                List<TipsMainVo> collect = allTips.stream().map(id -> {
                    TipsMainVo tipsMainVo = new TipsMainVo();
                    TipsMain tip = tipsMainService.getById(id);
                    BeanUtils.copyProperties(tip, tipsMainVo);
                    return tipsMainVo;
                }).collect(Collectors.toList());
                tipsMainVos.addAll(collect);
            }
        }
        if (!CollectionUtils.isEmpty(records)) {
            for (TipsMain tipsMain : records) {
                TipsMainVo vo = new TipsMainVo();
                BeanUtils.copyProperties(tipsMain,vo);
                //查询 是否有 tags
                QueryWrapper<TipsMainTagRel> wrapperTmp = new QueryWrapper<>();
                //update_time 降序  isAsc)是否升序排列 true=asc，false=desc
                //查询
                wrapperTmp.eq("tips_main_id", vo.getId());
                List<TipsMainTagRel> list = tipsMainTagRelService.list(wrapperTmp);
                if (!CollectionUtils.isEmpty(list)) {
                    List<TipsTag> tags = new ArrayList<>();
                    for (TipsMainTagRel rel : list) {
                        TipsTag tipsTag = tipsTagService.getById(rel.getTipsTagId());
                        tags.add(tipsTag);
                    }
                    vo.setTags(tags);
                    tipsMainVos.add(vo);
                }
            }
        }

        return new ApiResponse<>(tipsMainVos);
    }
    @RequestMapping(method = RequestMethod.POST, value = "/updateTips")
    public BaseApiResponse updateTips(@RequestBody TipsMainModel tipsMainModel) {

        if (!StringUtils.hasText(tipsMainModel.getContentMd()) || tipsMainModel.getId()==0) {
            return new BaseApiResponse();
        }
        try {
            TipsMain tips = tipsMainService.getById(tipsMainModel.getId());
            tips.setContentMd(tipsMainModel.getContentMd());
            tips.setUpdateTime(new Date());

            String tagStr = tipsMainModel.getTagStr();
            List<String> tagStrList = new ArrayList<>();
            List<TipsTag> tags = new ArrayList<>();
            if (StringUtils.hasText(tagStr)) {
                String[] split = tagStr.split(",");
                tagStrList = Arrays.asList(split);
            }
            if (!CollectionUtils.isEmpty(tagStrList)) {
                //说明有标签
                tips.setTagOrNot("1");
                tipsMainMapper.updateById(tips);

                //查询 tag 表 将 id 和 tag 对应查询出来 没有的话就新增
                for (String tagName : tagStrList) {
                    if (!StringUtils.hasText(tagName)) {
                        continue;
                    }
                    TipsTag tipsTag = tipsTagMapper.selectOne(new QueryWrapper<TipsTag>().eq("tag_name", tagName));
                    if (tipsTag == null) {
                        //新增
                        tipsTag = new TipsTag();
                        tipsTag.setTagName(tagName);
                        tipsTagMapper.insert(tipsTag);
                    }
                    tags.add(tipsTag);
                }
                //查询关联数据
                //查询 是否有 tags
                QueryWrapper<TipsMainTagRel> wrapperTmp = new QueryWrapper<>();
                //update_time 降序  isAsc) 是否升序排列 true=asc，false=desc
                //查询
                wrapperTmp.eq("tips_main_id", tips.getId());
                List<TipsMainTagRel> list = tipsMainTagRelService.list(wrapperTmp);
                //更新数据到关联表中。
                int index = 0;
                for (TipsTag tag: tags) {
                    if (index >= list.size()) {
                        TipsMainTagRel tipsMainTagRel = new TipsMainTagRel();
                        tipsMainTagRel.setTipsMainId(tips.getId());
                        tipsMainTagRel.setTipsTagId(tag.getId());
                        tipsMainTagRelService.save(tipsMainTagRel);
                    }else {
                        TipsMainTagRel tipsMainTagRel = list.get(index);
                        tipsMainTagRel.setTipsTagId(tag.getId());
                        tipsMainTagRelService.updateById(tipsMainTagRel);
                    }
                    index ++;
                }
                if (list.size() - index > 0) {
                    for (int i = index ; index < list.size() ;i ++) {
                        tipsMainTagRelService.removeById(list.get(i).getId());
                    }
                }
            }else {
                //说明没有标签
                tips.setTagOrNot("0");
                tipsMainMapper.updateById(tips);
            }

        }catch (Exception e) {
            return new BaseApiResponse(500, 500, "未知异常，请联系管理员！！！");
        }

        return new BaseApiResponse();
    }

}
